<template>
  <div class="checkout-form-container">
    <!-- 顶部步骤条（与审批页保持一致样式） -->
    <div class="steps">
      <div v-for="(s,i) in steps" :key="i" class="step" :class="{active: i < 1}">
        <div class="dot">{{ i+1 }}</div>
        <div class="name">{{ s }}</div>
        <div v-if="i<steps.length-1" class="line"/>
      </div>
    </div>

    <!-- 表单标题 -->
    <div class="form-title">
      <h2>填写申请信息</h2>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <el-form
        ref="checkoutFormRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="checkout-form"
      >
        <!-- ① 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">① 基本信息</h3>
          <div class="form-row">
            <el-form-item label="老人姓名" prop="elderlyName" required class="form-item">
              <el-input
                v-model="formData.elderlyName"
                placeholder="请选择"
                readonly
                @click="showElderlyDialog = true"
                class="elderly-input"
              >
                <template #suffix>
                  <el-icon class="el-input__icon">
                    <ArrowDown />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="老人身份证号" class="form-item">
              <el-input v-model="formData.elderlyIdCard" placeholder="老人身份证号" readonly />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="联系方式" class="form-item">
              <el-input v-model="formData.contact" placeholder="联系方式" readonly />
            </el-form-item>
            
            <el-form-item label="费用期限" class="form-item">
              <el-input v-model="formData.feePeriod" placeholder="费用期限" readonly />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="护理等级" class="form-item">
              <el-input v-model="formData.careLevel" placeholder="护理等级" readonly />
            </el-form-item>
            
            <el-form-item label="入住床位" class="form-item">
              <el-input v-model="formData.bedNumber" placeholder="入住床位" readonly />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="签约合同" class="form-item">
              <el-input v-model="formData.contract" placeholder="签约合同" readonly />
            </el-form-item>
            
            <el-form-item label="养老顾问" class="form-item">
              <el-input v-model="formData.consultant" placeholder="养老顾问" readonly />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="护理员" class="form-item">
              <el-input v-model="formData.caregiver" placeholder="护理员" readonly />
            </el-form-item>
          </div>
        </div>

        <!-- ② 申请信息 -->
        <div class="form-section">
          <h3 class="section-title">② 申请信息</h3>
          
          <div class="form-row">
            <el-form-item label="退住日期" prop="checkoutDate" required class="form-item">
              <el-date-picker
                v-model="formData.checkoutDate"
                type="date"
                placeholder="选择退住日期"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                class="date-picker"
              />
            </el-form-item>
            
            <el-form-item label="退住原因" prop="checkoutReason" required class="form-item">
              <el-select
                v-model="formData.checkoutReason"
                placeholder="请选择"
                class="reason-select"
              >
                <el-option
                  v-for="reason in checkoutReasons"
                  :key="reason.value"
                  :label="reason.label"
                  :value="reason.value"
                />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="备注" prop="remark" class="form-item full-width">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入"
                maxlength="100"
                show-word-limit
                class="remark-textarea"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel" class="cancel-btn">返回</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting" class="submit-btn">
          提交
        </el-button>
      </div>
    </div>

    <!-- 老人选择弹窗 -->
    <el-dialog
      v-model="showElderlyDialog"
      title="选择老人"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="elderly-dialog-content">
        <!-- 搜索区域 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入老人姓名或身份证号搜索"
            @input="handleSearch"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 老人列表 -->
        <div class="elderly-list">
          <el-table
            :data="filteredElderlyList"
            @row-click="selectElderly"
            highlight-current-row
            v-loading="loadingElderly"
            height="400"
          >
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="idCard" label="身份证号" width="180" />
            <el-table-column prop="gender" label="性别" width="80" />
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="phone" label="联系电话" width="140" />
            <el-table-column prop="careLevel" label="护理等级" width="100" />
            <el-table-column prop="bedNumber" label="床位号" width="100" />
            <el-table-column prop="caregiver" label="护理员" width="100" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showElderlyDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmElderlySelection" :disabled="!selectedElderlyRow">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Search } from '@element-plus/icons-vue'
import { listElderly, getElderly } from '@/api/system/elderly'
import { addOut_management, getContractByElderlyId } from '@/api/system/out_management'
import { createCheckoutNotification } from '@/api/system/messagecenter'

const router = useRouter()

// 步骤条（与审批页一致）
const steps = ['申请退住','申请审批','解除合同','调整账单','账单审批','退住审批','费用清算']

// 表单数据
const formData = reactive({
  elderlyName: '',
  elderlyId: '',
  elderlyIdCard: '',
  contact: '',
  feePeriod: '',
  careLevel: '',
  bedNumber: '',
  contract: '',
  consultant: '',
  caregiver: '',
  checkoutDate: '',
  checkoutReason: '',
  remark: '',
  // 隐藏字段，用于提交
  bedId: null,
  checkInManagementId: null,
  creatorId: null
})

// 表单验证规则
const formRules = {
  elderlyName: [
    { required: true, message: '请选择老人', trigger: 'change' }
  ],
  checkoutDate: [
    { required: true, message: '请选择退住日期', trigger: 'change' }
  ],
  checkoutReason: [
    { required: true, message: '请选择退住原因', trigger: 'change' }
  ]
}

// 退住原因选项 - 使用中文作为value，确保数据库存储和显示一致
const checkoutReasons = [
  { value: '老人个人原因', label: '老人个人原因' },
  { value: '护理质量不高', label: '护理质量不高' },
  { value: '服务不周', label: '服务不周' },
  { value: '管理混乱', label: '管理混乱' },
  { value: '费用高昂', label: '费用高昂' },
  { value: '违规退住', label: '违规退住' },
  { value: '其他', label: '其他' }
]

// 弹窗相关
const showElderlyDialog = ref(false)
const elderlyList = ref([])
const loadingElderly = ref(false)
const searchKeyword = ref('')
const selectedElderlyRow = ref(null)

// 选中的老人信息
const selectedElderly = ref(null)

// 表单引用
const checkoutFormRef = ref(null)
const submitting = ref(false)

// 计算属性 - 过滤后的老人列表
const filteredElderlyList = computed(() => {
  if (!searchKeyword.value) {
    return elderlyList.value
  }
  return elderlyList.value.filter(elderly => 
    elderly.name.includes(searchKeyword.value) || 
    elderly.idCard.includes(searchKeyword.value)
  )
})

// 禁用日期函数 - 禁用当天之前的日期（可以选择当天及之后的日期）
const disabledDate = (time) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 设置为当天0点
  return time.getTime() < today.getTime()
}

// 加载老人列表
const loadElderlyList = async () => {
  loadingElderly.value = true
  try {
    // 获取所有老人信息
    const response = await listElderly({
      pageNum: 1,
      pageSize: 1000
    })
    
    // 过滤出已入住且未请假的老人
    const allElderly = response.rows || []
    const availableElderly = allElderly.filter(elderly => {
      // 检查是否有床位（表示已入住）
      const hasBed = elderly.bedId && elderly.bedId > 0
      
      // 检查是否正在请假（需要根据实际业务逻辑调整）
      // 这里假设通过关联的请假记录来判断
      const isOnLeave = elderly.leaveRequestList && elderly.leaveRequestList.some(leave => 
        leave.leaveStatus === '3' || leave.leaveStatus === 'approved' // 请假中或已批准请假
      )
      
      // 检查是否正在申请退住或已退住
      const isCheckout = elderly.checkInManagementList && elderly.checkInManagementList.some(checkin => 
        checkin.status === 'checkout_pending' || checkin.status === 'checkout_completed'
      )
      
      return hasBed && !isOnLeave && !isCheckout
    })
    
    elderlyList.value = availableElderly
  } catch (error) {
    console.error('加载老人列表失败:', error)
    ElMessage.error('加载老人列表失败')
  } finally {
    loadingElderly.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑在计算属性中处理
}

// 选择老人行
const selectElderly = (row) => {
  selectedElderlyRow.value = row
}

// 确认选择老人
const confirmElderlySelection = async () => {
  if (selectedElderlyRow.value) {
    try {
      // 调用接口获取老人详细信息
      const response = await getElderly(selectedElderlyRow.value.id)
      const elderlyDetail = response.data
      
      selectedElderly.value = selectedElderlyRow.value
      formData.elderlyName = elderlyDetail.name || ''
      formData.elderlyId = elderlyDetail.id
      formData.elderlyIdCard = elderlyDetail.idCard || ''
      formData.contact = elderlyDetail.contact || ''
      formData.careLevel = elderlyDetail.careLevel || ''
      formData.bedNumber = elderlyDetail.bedNumber || ''
      formData.consultant = elderlyDetail.consultant || ''
      formData.caregiver = elderlyDetail.caregiver || ''
      
      // 保存隐藏字段（用于提交）
      formData.bedId = elderlyDetail.bedId || null
      formData.checkInManagementId = elderlyDetail.checkInManagementId || null
      formData.creatorId = elderlyDetail.creatorId || null
      
      // 设置费用期限
      if (elderlyDetail.feeStartDate && elderlyDetail.feeEndDate) {
        formData.feePeriod = `${elderlyDetail.feeStartDate} 至 ${elderlyDetail.feeEndDate}`
      } else {
        formData.feePeriod = ''
      }
      
      // 设置合同信息 - 通过API获取合同详情
      try {
        console.log('=== 开始获取合同信息 ===')
        console.log('老人ID:', elderlyDetail.id)
        
        const contractResponse = await getContractByElderlyId(elderlyDetail.id)
        console.log('合同API响应:', contractResponse)
        
        if (contractResponse.code === 200 && contractResponse.data && contractResponse.data.contractName) {
          console.log('合同数据:', contractResponse.data)
          console.log('合同名称:', contractResponse.data.contractName)
          formData.contract = contractResponse.data.contractName
        } else {
          console.log('未找到合同数据，显示无合同')
          formData.contract = '无合同'
        }
        
        console.log('最终合同显示:', formData.contract)
        console.log('=== 合同信息获取完成 ===')
      } catch (contractError) {
        console.error('获取合同信息失败:', contractError)
        formData.contract = '获取失败'
      }
      
      showElderlyDialog.value = false
    } catch (error) {
      console.error('获取老人详细信息失败:', error)
      ElMessage.error('获取老人信息失败，请重试')
    }
  }
}

// 验证费用期限
const validateFeePeriod = (checkoutDate) => {
  if (!selectedElderly.value || !checkoutDate) {
    return true
  }
  
  // 根据入住记录验证费用期限
  if (selectedElderly.value.checkInManagementList && selectedElderly.value.checkInManagementList.length > 0) {
    const latestCheckIn = selectedElderly.value.checkInManagementList[0] // 获取最新的入住记录
    
    // 检查退住日期是否在入住期间内
    const checkInStart = new Date(latestCheckIn.checkInStartTime)
    const checkInEnd = latestCheckIn.checkInEndTime ? new Date(latestCheckIn.checkInEndTime) : null
    const checkoutDateObj = new Date(checkoutDate)
    
    // 退住日期不能早于入住开始时间
    if (checkoutDateObj < checkInStart) {
      return false
    }
    
    // 如果有入住结束时间，退住日期不能晚于入住结束时间
    if (checkInEnd && checkoutDateObj > checkInEnd) {
      return false
    }
  }
  
  return true
}

// 生成唯一的退住单号
const generateCheckOutNo = () => {
  // COUT + 4位随机数字（确保唯一性）
  const timestamp = new Date().getTime().toString()
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  return 'COUT' + random
}

// 提交表单
const handleSubmit = async () => {
  if (!checkoutFormRef.value) return
  
  try {
    // 验证表单
    await checkoutFormRef.value.validate()
    
    // 验证必要字段
    if (!formData.elderlyId) {
      ElMessage.error('请先选择老人')
      return
    }
    
    if (!formData.checkInManagementId) {
      ElMessage.error('未找到老人的入住管理记录')
      return
    }
    
    // 验证费用期限
    if (!validateFeePeriod(formData.checkoutDate)) {
      ElMessage.error('请在费用期限内发起退住申请')
      return
    }
    
    submitting.value = true
    
    // 准备提交数据（按照数据库表结构）
    const submitData = {
      // 退住单号：COUT + 4位随机数字
      checkOutNo: generateCheckOutNo(),
      // 老人外键编号
      elderlyId: formData.elderlyId,
      // 入住管理外键
      checkInManagementId: formData.checkInManagementId,
      // 床位外键编号
      bedId: formData.bedId,
      // 退住日期
      checkOutDate: formData.checkoutDate,
      // 退住原因
      checkOutReason: formData.checkoutReason,
      // 备注
      remark: formData.remark || null,
      // 创建人（护理员ID）
      creator: formData.creatorId,
      // 创建时间和更新时间由后端自动设置
      // is_deleted 默认为0（后端设置）
    }
    
    console.log('提交数据:', submitData)
    
    // 提交到后端
    const response = await addOut_management(submitData)
    console.log('退住申请提交响应:', response)
    
    ElMessage.success('退住申请提交成功！')
    
    // ✅ 创建退住申请通知消息
    try {
      console.log('=== 创建退住申请通知消息 ===')
      const applicationId = response.data?.id || Date.now()
      const elderlyName = formData.elderlyName || '未知老人'

      console.log('申请ID:', applicationId)
      console.log('老人姓名:', elderlyName)

      const messageData = {
        applicationId: applicationId,
        elderlyName: elderlyName
      }

      console.log('消息数据:', messageData)

      const messageResponse = await createCheckoutNotification(messageData)
      console.log('消息创建响应:', messageResponse)

      if (messageResponse.code === 200) {
        console.log('✅ 退住申请通知消息创建成功！')
        ElMessage.success('已生成退住申请通知消息！')

        // ✅ 刷新页面顶部铃铛图标的未读消息数
        try {
          console.log('=== 刷新未读消息数 ===')
          if (window.refreshUnreadMessageCount) {
            window.refreshUnreadMessageCount()
            console.log('✅ 未读消息数已刷新！')
          } else {
            console.log('⚠️ 全局刷新方法未找到，尝试触发事件')
            window.dispatchEvent(new CustomEvent('unread-refresh'))
          }
        } catch (refreshError) {
          console.error('刷新未读消息数失败:', refreshError)
        }
      } else {
        console.error('❌ 退住申请通知消息创建失败:', messageResponse.msg)
        ElMessage.warning('退住申请提交成功，但通知消息创建失败：' + messageResponse.msg)
      }
    } catch (messageError) {
      console.error('创建退住申请通知消息异常:', messageError)
      ElMessage.warning('退住申请提交成功，但通知消息创建异常：' + messageError.message)
    }

    // 保存完整的申请数据到sessionStorage，供审批页面使用
    const approvalData = {
      // 基本信息
      elderlyNo: 'COUT' + Date.now().toString().slice(-4), // 生成单据编号
      elderlyName: formData.elderlyName,
      elderlyIdCard: formData.elderlyIdCard,
      contact: formData.contact,
      feePeriod: formData.feePeriod,
      careLevel: formData.careLevel,
      bedNumber: formData.bedNumber,
      contract: formData.contract,
      consultant: formData.consultant,
      caregiver: formData.caregiver,
      // 申请信息
      checkoutDate: formData.checkoutDate,
      checkoutReason: formData.checkoutReason,
      remark: formData.remark,
      applicantName: formData.caregiver || '护理员',
      submitTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-'),
      // 业务数据
      businessId: response.data?.id || Date.now(), // 使用后端返回的ID
      elderlyId: formData.elderlyId,
      checkInManagementId: formData.checkInManagementId,
      bedId: formData.bedId
    }
    
    console.log('保存审批数据:', approvalData)
    
    // 为每个申请创建唯一的数据存储键
    const businessId = response.data?.id || Date.now() + Math.random().toString(36).substr(2, 9)
    const storageKey = `checkout_approval_data_${businessId}`
    console.log('后端返回的ID:', response.data?.id)
    console.log('生成的业务ID:', businessId)
    console.log('使用存储键:', storageKey)
    
    sessionStorage.setItem(storageKey, JSON.stringify(approvalData))
    console.log('数据已保存到特定存储键:', storageKey)
    
    // 同时保存到通用键，作为备用方案
    sessionStorage.setItem('checkout_approval_data', JSON.stringify(approvalData))
    console.log('数据已保存到通用存储键: checkout_approval_data')
    
    // ✅ 提交成功后返回退住管理界面
    console.log('退住申请提交成功，返回退住管理界面')
    router.push({
      path: '/system/out_management'
    })
    
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败：' + (error.message || '请重试'))
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消吗？未保存的数据将会丢失。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    })
    router.back()
  } catch {
    // 用户取消操作
  }
}

// 初始化
onMounted(() => {
  // 设置默认退住日期为当前日期
  const today = new Date()
  formData.checkoutDate = today.toISOString().split('T')[0]
  
  // 加载老人列表
  loadElderlyList()
})
</script>

<style scoped>
.checkout-form-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 顶部步骤条（与审批页统一） */
.steps{display:flex;align-items:center;background:#fff;border:1px solid #ebeef5;border-radius:4px;padding:10px 12px;margin-bottom:14px}
.step{display:flex;align-items:center;color:#a8abb2}
.dot{width:24px;height:24px;border-radius:50%;border:2px solid #dcdfe6;display:flex;align-items:center;justify-content:center;margin-right:6px}
.step.active .dot{border-color:#409eff;color:#409eff}
.name{margin-right:8px}
.line{width:56px;height:1px;background:#e9eaef;margin:0 8px}

/* 表单标题 */
.form-title {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-title h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 500;
}

/* 表单容器 */
.form-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 表单区域 */
.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

/* 表单行 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  flex: 1;
  margin-bottom: 0;
}

.form-item.full-width {
  flex: 2;
}

/* 表单项样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.elderly-input {
  cursor: pointer;
}

.date-picker,
.reason-select {
  width: 100%;
}

.remark-textarea {
  width: 100%;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  width: 100px;
  height: 40px;
}

.submit-btn {
  width: 100px;
  height: 40px;
}

/* 弹窗样式 */
.elderly-dialog-content {
  padding: 10px 0;
}

.search-section {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
}

.elderly-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    padding: 20px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-item {
    margin-bottom: 20px;
  }
  
  .progress-steps {
    flex-direction: column;
    gap: 20px;
  }
  
  .step-connector {
    display: none;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .cancel-btn,
  .submit-btn {
    width: 100%;
    max-width: 200px;
  }
}

@media (max-width: 1200px) {
  .progress-steps {
    flex-wrap: wrap;
    justify-content: flex-start;
  }
  
  .step-connector {
    width: 20px;
  }
}
</style>
